from typing import Optional

from PyQt5.QtCore import Qt
from PyQt5.QtGui import QPixmap
from PyQt5.QtWidgets import QLabel


class ResizablePicture(QLabel):
    __pixmap = None

    def __init__(self, parent=None):
        super(ResizablePicture, self).__init__(parent)
        # self.setSizePolicy(QSizePolicy.Ignored, QSizePolicy.Ignored)
        self.setAlignment(Qt.AlignCenter)
        # self.setScaledContents(True)

    def resizeEvent(self, event):
        super(ResizablePicture, self).resizeEvent(event)
        if self.__pixmap is not None:
            self.setPixmap(self.__pixmap)

    def _setPixmapResize(self, pixmap: Optional[QPixmap]):
        if pixmap is None:
            super().setPixmap(QPixmap(''))
            return

        if isinstance(pixmap, QPixmap):
            pixmap = pixmap.scaled(self.width(), self.height(), Qt.KeepAspectRatio, Qt.SmoothTransformation)
        super().setPixmap(pixmap)

    def setPixmap(self, pixmap: Optional[QPixmap]):
        self.__pixmap = pixmap
        self._setPixmapResize(pixmap)

    def clear(self):
        self.setPixmap(None)
